<?php
/**
 * TODO: Add loging
 *
 */

/**
 * @see Zend_Loader
 */
require_once 'Zend/Loader.php';
require_once 'Zend/Gdata.php';
require_once 'Zend/Debug.php';


/**
 * @see Zend_Gdata_ClientLogin
 */
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');


/**
 * @see Zend_Gdata_Finance
 */
Zend_Loader::loadClass('Zend_Gdata_Finance');


/**
 * Returns a HTTP client object with the appropriate headers for communicating
 * with Google using the ClientLogin credentials supplied.
 *
 * @param  string $user The username, in e-mail address format, to authenticate
 * @param  string $pass The password for the user specified
 * @return Zend_Http_Client
 */

function getClientLoginHttpClient($user, $pass)
{
	$service = Zend_Gdata_Finance::AUTH_SERVICE_NAME;

	$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
	return $client;
}

/**
 * Display list of valid commands.
 *
 * @param  string $executable The name of the current script. This is usually av
 ailable as $argv[0].
 * @return void
 */
function displayHelp($executable)
{
	echo "Usage: php {$executable} [<username>] [<password>] " .
        "[<action>] [<portfolioName>] [<currency>] \n";
	echo "where <action> can be add or list\n\n";

}


if (isset($argc) && $argc >= 4)
{
	try {
		$client = getClientLoginHttpClient($argv[1], $argv[2]);
		$gdata = new Zend_Gdata_Finance($client);
		$gdata->enableRequestDebugLogging('/tmp/zend_debug.txt');
	} catch (Zend_Gdata_App_AuthException $e) {
		echo "Error: Unable to authenticate. Please check your";
		echo " credentials.\n";
		exit(1);
	}

}
else
{
	displayHelp($argv[0]);
	exit(1);
}
if (isset($argv[5] ))
$currency=$argv[5];
else
$currency="USD";

try
{
	if ($argv[3] == "add")
	{
	$entry=$gdata->addPortfolio($argv[4],$currency);
	echo $entry->getId() . "\n";
	}
	else if ($argv[3] == "del")
	{
	$gdata->delPortfolio($argv[4]);
	}
	else if ($argv[3] == "list")
	{
		$feed=$gdata->getPortfolioFeed();
# Iterate over the portfolio entries in the feed and display each portfolio  title.
#    Zend_Debug::dump($feed);
  foreach ($feed->entries as $entry)
  	{
    	  echo $entry->title . "\t" .  $entry->id ."\n";
	 }	
	}
}
catch ( Zend_Gdata_App_HttpException $e )
{
	echo $e->getMessage() . "\n";
}

?>